package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.*;

/**
 * @author lizuhu
 * @description
 * @date 2021/8/31 9:42
 */
public class ServerChannel implements Runnable {
    private ObjectOutputStream oos;
    private ObjectInputStream ois;
    private Socket socket;
    private String userName;
    public static Map<String, ObjectOutputStream> clients = new HashMap<>();

    public ServerChannel(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            ois = new ObjectInputStream(socket.getInputStream());
            oos = new ObjectOutputStream(socket.getOutputStream());
            userName = (String) ois.readObject();
            String msg;
            clients.put(userName, oos);
            System.out.println(userName + "进入聊天室！");
            for (ObjectOutputStream oos : clients.values()) {
                oos.writeObject("系统信息：欢迎" + userName + "进入聊天室，当前在线人数：" + clients.size());
            }
            while (true) {
                //减少cpu占用
                Thread.sleep(100);
                //接收的消息
                msg = (String) ois.readObject();
                System.out.println(userName + "说：" + msg);
                if (msg.contains("@")) {
                    privateChat(userName, msg);
                } else if (msg.contains("bye")) {
                    exit(userName);
                    break;
                } else {
                    groupChat(userName, msg);
                }
            }
        } catch (Exception e) {
            try {
                //客户端抛出异常，将socket关闭，并将clients中的键值删除
                socket.close();
                clients.remove(userName);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    //群聊
    private void groupChat(String userName, String msg) throws IOException {
        for (ObjectOutputStream oos : clients.values()) {
            oos.writeObject(userName + "对所有人说：" + msg);
            oos.flush();
        }
    }

    //私聊
    private void privateChat(String userName, String msg) throws IOException {
        ObjectOutputStream oos = clients.get(msg.substring(1, msg.lastIndexOf(":")));
        oos.writeObject(userName + "私信你说：" + msg.substring(msg.indexOf(":") + 1));
        oos.flush();
    }

    //离开聊天室
    private void exit(String userName) throws Exception {
        for (ObjectOutputStream oos : clients.values()) {
            oos.writeObject("系统消息：" + userName + "下线了");
        }
        clients.remove(userName);
    }

}
